﻿using System;

using System.Collections;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Global.Class.Library;
using BusinessLogicLayer;
using DataAccessLayer;
using DataTransferObject;
using System.Globalization;
using BrightIdeasSoftware;
using Equin.ApplicationFramework;

namespace PresentationLayer
{
    public partial class InMarket : Form, IMergeToolStrip, ICallToolStrip
    {

        #region <Implement Interface>

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public GlobalEnum.TaskID TaskID
        {
            get { return this.inMarketBLL.TaskID; }
        }


        public ToolStrip ChildToolStrip
        {
            get
            {
                return this.toolStripChildForm;
            }
            set
            {
                this.toolStripChildForm = value;
            }
        }





        #region Context toolbar


        public bool IsDirty
        {
            get { return this.inMarketBLL.IsDirty; }
        }

        public bool IsValid
        {
            get { return this.inMarketBLL.IsValid; }
        }

        public bool Closable
        {
            get { return true; }
        }

        public bool Loadable
        {
            get { return true; }
        }

        public bool Newable
        {
            get { return !this.inMarketBLL.ReadOnly; }
        }

        public bool Editable
        {
            get { return this.inMarketBLL.Editable; }
        }

        public bool Deletable
        {
            get { return this.inMarketBLL.Editable; }
        }

        public bool Importable
        {
            get { return true; }
        }

        public bool Exportable
        {
            get { return true; }
        }

        public bool Verifiable
        {
            get { return this.inMarketBLL.Verifiable; }
        }

        public bool Unverifiable
        {
            get { return this.inMarketBLL.Unverifiable; }
        }

        public bool Printable
        {
            get { return false; }
        }

        public bool Searchable
        {
            get { return true; }
        }

        /// <summary>
        /// Edit Mode: True, Read Mode: False
        /// </summary>
        private bool editableMode;
        private int lastInMarketID;
        public bool EditableMode { get { return this.editableMode; } }
        /// <summary>
        /// This reverse of the EditableMode
        /// </summary>
        public bool ReadonlyMode { get { return !this.editableMode; } }

        /// <summary>
        /// Set the editableMode
        /// </summary>
        /// <param name="editableMode"></param>
        private void SetEditableMode(bool editableMode)
        {
            if (this.editableMode != editableMode)
            {
                this.lastInMarketID = this.inMarketBLL.InMarketID;
                this.editableMode = editableMode;
                this.NotifyPropertyChanged("EditableMode");
                this.NotifyPropertyChanged("ReadonlyMode");

                this.naviGroupDetails.Expanded = editableMode;
            }
        }


        private void CancelDirty(bool restoreSavedData)
        {
            try
            {
                if (restoreSavedData || this.inMarketBLL.InMarketID <= 0)
                    this.inMarketBLL.Fill(this.lastInMarketID);

                this.SetEditableMode(false);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }



        #endregion Context toolbar



        #region ICallToolStrip

        public void Escape()
        {
            if (this.EditableMode)
            {
                if (this.IsDirty)
                {
                    DialogResult dialogResult = MessageBox.Show(this, "Do you want to save your change?", "Warning", MessageBoxButtons.YesNoCancel);
                    if (dialogResult == DialogResult.Yes)
                    {
                        this.Save();
                        if (!this.IsDirty) this.CancelDirty(false);
                    }
                    else if (dialogResult == DialogResult.No)
                    {
                        this.CancelDirty(true);
                    }
                    else
                        return;
                }
                else
                    this.CancelDirty(false);
            }
            else
                this.Close(); //Unload this module
        }

        //Can phai xem lai trong VB de xem lai this.SetEditableMode () khi can thiet

        public void Loading()
        {
            this.GetMasterList();
        }

        public void New()
        {
            this.inMarketBLL.New();
            this.SetEditableMode(true);
        }

        public void Edit()
        {
            this.SetEditableMode(true);
        }

        public void Save()
        {
            this.inMarketBLL.Save();
            this.GetMasterList();
        }

        public void Delete()
        {
            DialogResult dialogResult = MessageBox.Show(this, "Are you sure you want to delete " + this.inMarketBLL.InMarketMaster.Reference + "?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Stop);
            if (dialogResult == DialogResult.Yes)
            {
                try
                {
                    this.inMarketBLL.Delete();
                    this.GetMasterList();
                }
                catch (Exception exception)
                {
                    GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
                }
            }
        }

        public void Import()
        {
            ImportExcel();
        }

        public void Export()
        {
            try
            {
                if (this.ActiveControl.Equals(this.dataListViewMaster))
                {
                    DataTable dataTableExport;
                    dataTableExport = this.dataListViewMaster.DataSource as DataTable;
                    if (dataTableExport != null) CommonFormAction.Export(dataTableExport);
                }
                else
                {
                    List<InMarketDetail> listExport;
                    listExport = this.inMarketBLL.InMarketDetailList.ToList();
                    if (listExport != null) CommonFormAction.Export(listExport);
                }
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        public void Verify()
        {
            MessageBox.Show("Verify");
        }

        public void Print(PrintDestination printDestination)
        {
            MessageBox.Show("Print");
        }

        public void SearchText(string searchText)
        {
            CommonFormAction.OLVFilter(this.dataListViewMaster, searchText);
        }

        #endregion


        #endregion <Implement Interface>








        #region <Storage>
        private InMarketBLL inMarketBLL;

        #endregion <Storage>


        public InMarket()
        {
            try
            {
                InitializeComponent();

                this.inMarketBLL = new InMarketBLL();

                this.inMarketBLL.PropertyChanged += new PropertyChangedEventHandler(inMarketBLL_PropertyChanged);                

            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        void inMarketBLL_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            this.NotifyPropertyChanged(e.PropertyName);
        }


        private void InMarketBLL_Load(object sender, EventArgs e)
        {
            try
            {
                InitializeCommonControlBinding();

                InitializeDataGridBinding();

                InitializeReadOnlyModeBinding();
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }


        #region <InitializeBinding>

        Binding orderOrReturnIDBinding;
        Binding customerIDBinding;
        Binding distributorIDBinding;
        Binding salesmenIDBinding;
        Binding promotionCampaignIDBinding;
        Binding returnCategoryIDBinding;
        Binding refuseCategoryIDBinding;

       
        Binding referenceBinding;
        Binding descriptionBinding;
        Binding otherBinding;

        Binding inMarketDateBinding;
        Binding entryDateBinding;

        Binding isDirtyBinding;
        Binding isDirtyBLLBinding;

        private void InitializeCommonControlBinding()
        {
            CommonMetaList commonMetaList = new CommonMetaList();


            ERmgrUIP.ListOrderOrReturnDataTable listOrderOrReturnDataTable = commonMetaList.GetOrderOrReturn();
            this.comboBoxOrderOrReturnID.DataSource = listOrderOrReturnDataTable;
            this.comboBoxOrderOrReturnID.DisplayMember = listOrderOrReturnDataTable.DescriptionColumn.ColumnName;
            this.comboBoxOrderOrReturnID.ValueMember = listOrderOrReturnDataTable.OrderOrReturnIDColumn.ColumnName;
            this.orderOrReturnIDBinding = this.comboBoxOrderOrReturnID.DataBindings.Add("SelectedValue", this.inMarketBLL.InMarketMaster, "OrderOrReturnID", true);


            ERmgrUIP.ListCustomerNameDataTable listCustomerNameDataTable = commonMetaList.GetCustomerName();
            this.comboBoxCustomerID.DataSource = listCustomerNameDataTable;
            this.comboBoxCustomerID.DisplayMember = listCustomerNameDataTable.DescriptionOfficialColumn.ColumnName;
            this.comboBoxCustomerID.ValueMember = listCustomerNameDataTable.CustomerIDColumn.ColumnName;
            this.customerIDBinding = this.comboBoxCustomerID.DataBindings.Add("SelectedValue", this.inMarketBLL.InMarketMaster, "CustomerID", true);

            ERmgrUIP.ListDistributorNameDataTable listDistributorNameDataTable = commonMetaList.GetDistributorName();
            this.comboBoxDistributorID.DataSource = listDistributorNameDataTable;
            this.comboBoxDistributorID.DisplayMember = listDistributorNameDataTable.DescriptionOfficialColumn.ColumnName;
            this.comboBoxDistributorID.ValueMember = listDistributorNameDataTable.DistributorIDColumn.ColumnName;
            this.distributorIDBinding = this.comboBoxDistributorID.DataBindings.Add("SelectedValue", this.inMarketBLL.InMarketMaster, "DistributorID", true);

            ERmgrUIP.ListSalesmenNameDataTable listSalesmenNameDataTable = commonMetaList.GetSalesmenName();
            this.comboBoxSalesmenID.DataSource = listSalesmenNameDataTable;
            this.comboBoxSalesmenID.DisplayMember = listSalesmenNameDataTable.DescriptionOfficialColumn.ColumnName;
            this.comboBoxSalesmenID.ValueMember = listSalesmenNameDataTable.SalesmenIDColumn.ColumnName;
            this.salesmenIDBinding = this.comboBoxSalesmenID.DataBindings.Add("SelectedValue", this.inMarketBLL.InMarketMaster, "SalesmenID", true);

            ERmgrUIP.ListPromotionCampaignDataTable listPromotionCampaignDataTable = commonMetaList.GetPromotionCampaign();
            this.comboBoxPromotionCampaignID.DataSource = listPromotionCampaignDataTable;
            this.comboBoxPromotionCampaignID.DisplayMember = listPromotionCampaignDataTable.DescriptionColumn.ColumnName;
            this.comboBoxPromotionCampaignID.ValueMember = listPromotionCampaignDataTable.PromotionCampaignIDColumn.ColumnName;
            this.promotionCampaignIDBinding = this.comboBoxPromotionCampaignID.DataBindings.Add("SelectedValue", this.inMarketBLL.InMarketMaster, "PromotionCampaignID", true);

            ERmgrUIP.ListCategoryReturnDataTable listCategoryReturnDataTable = commonMetaList.GetCategoryReturn();
            this.comboBoxReturnCategoryID.DataSource = listCategoryReturnDataTable;
            this.comboBoxReturnCategoryID.DisplayMember = listCategoryReturnDataTable.DescriptionColumn.ColumnName;
            this.comboBoxReturnCategoryID.ValueMember = listCategoryReturnDataTable.ReturnCategoryIDColumn.ColumnName;
            this.returnCategoryIDBinding = this.comboBoxReturnCategoryID.DataBindings.Add("SelectedValue", this.inMarketBLL.InMarketMaster, "ReturnCategoryID", true);

            ERmgrUIP.ListCategoryRefuseDataTable listCategoryRefuseDataTable = commonMetaList.GetCategoryRefuse();
            this.comboBoxRefuseCategoryID.DataSource = listCategoryRefuseDataTable;
            this.comboBoxRefuseCategoryID.DisplayMember = listCategoryRefuseDataTable.DescriptionColumn.ColumnName;
            this.comboBoxRefuseCategoryID.ValueMember = listCategoryRefuseDataTable.RefuseCategoryIDColumn.ColumnName;
            this.refuseCategoryIDBinding = this.comboBoxRefuseCategoryID.DataBindings.Add("SelectedValue", this.inMarketBLL.InMarketMaster, "RefuseCategoryID", true);

            


            this.referenceBinding = this.textBoxReference.DataBindings.Add("Text", this.inMarketBLL.InMarketMaster, "Reference", true);
            this.descriptionBinding = this.textBoxDescription.DataBindings.Add("Text", this.inMarketBLL.InMarketMaster, "Description", true);
            this.otherBinding = this.textBoxRemarks.DataBindings.Add("Text", this.inMarketBLL.InMarketMaster, "Other", true);


            this.inMarketDateBinding = this.dateTimePickerInMarketDate.DataBindings.Add("Value", this.inMarketBLL.InMarketMaster, "InMarketDate", true);
            this.entryDateBinding = this.dateTimePickerEntryDate.DataBindings.Add("Value", this.inMarketBLL.InMarketMaster, "EntryDate", true);


            this.isDirtyBinding = this.checkBoxIsDirty.DataBindings.Add("Checked", this.inMarketBLL.InMarketMaster, "IsDirty", true);
            this.isDirtyBLLBinding = this.checkBoxIsDirtyBLL.DataBindings.Add("Checked", this.inMarketBLL, "IsDirty", true);


            
            this.orderOrReturnIDBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.customerIDBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.distributorIDBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.salesmenIDBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.promotionCampaignIDBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.returnCategoryIDBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.refuseCategoryIDBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);

            
            this.referenceBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.descriptionBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.otherBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);

            this.inMarketDateBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.entryDateBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);

            
            this.isDirtyBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);
            this.isDirtyBLLBinding.BindingComplete += new BindingCompleteEventHandler(CommonControl_BindingComplete);

            this.naviGroupDetails.DataBindings.Add("ExpandedHeight", this.numericUpDownSizingDetail, "Value", true, DataSourceUpdateMode.OnPropertyChanged);
            this.numericUpDownSizingDetail.Minimum = this.naviGroupDetails.HeaderHeight * 2;
            this.numericUpDownSizingDetail.Maximum = this.naviGroupDetails.Height + this.dataListViewMaster.Height;

            this.tableLayoutPanelMaster.ColumnStyles[this.tableLayoutPanelMaster.ColumnCount - 1].SizeType = SizeType.Absolute; this.tableLayoutPanelMaster.ColumnStyles[this.tableLayoutPanelMaster.ColumnCount - 1].Width = 10;
            this.tableLayoutPanelExtend.ColumnStyles[this.tableLayoutPanelExtend.ColumnCount - 1].SizeType = SizeType.Absolute; this.tableLayoutPanelExtend.ColumnStyles[this.tableLayoutPanelExtend.ColumnCount - 1].Width = 10;

            this.errorProviderMaster.DataSource = this.inMarketBLL.InMarketMaster;
        }


        private void CommonControl_BindingComplete(object sender, BindingCompleteEventArgs e)
        {
            if (e.BindingCompleteState == BindingCompleteState.Exception) { GlobalExceptionHandler.ShowExceptionMessageBox(this, e.ErrorText); e.Cancel = true; }
        }

        private void numericUpDownSizingDetail_ValueChanged(object sender, EventArgs e)
        {
            this.naviGroupDetails.Expand();
        }

        private void naviGroupDetails_HeaderMouseClick(object sender, MouseEventArgs e)
        {
            this.numericUpDownSizingDetail.Visible = this.naviGroupDetails.Expanded;
            this.toolStripNaviGroupDetails.Visible = this.naviGroupDetails.Expanded;
        }

        private void toolStripButtonShowDetailsExtend_Click(object sender, EventArgs e)
        {
            this.naviGroupDetailsExtend.Expanded = !this.naviGroupDetailsExtend.Expanded;
            this.toolStripButtonShowDetailsExtend.Image = this.naviGroupDetailsExtend.Expanded ? ResourceIcon.Chevron_Collapse.ToBitmap() : ResourceIcon.Chevron_Expand.ToBitmap();
        }


        private void GetMasterList()
        {
            this.dataListViewMaster.SetNativeBackgroundTiledImage(global::PresentationLayer.Properties.Resources.Background);

            foreach (OLVColumn olvColumn in dataListViewMaster.Columns) { olvColumn.Renderer = null; }

            DataTable dataTableInMarketListing = this.inMarketBLL.InMarketListing(GlobalVariables.GlobalOptionSetting.LowerFillterDate, GlobalVariables.GlobalOptionSetting.UpperFillterDate);
            dataTableInMarketListing.TableName = "InMarketListing";

            DataSet bindingDataSet = new DataSet();
            bindingDataSet.Tables.Add(dataTableInMarketListing);

            this.dataListViewMaster.AutoGenerateColumns = false;
            this.dataListViewMaster.DataSource = dataTableInMarketListing;
        }

        private void InitializeDataGridBinding()
        {

            this.GetMasterList();



            #region <dataGridViewDetail>

            CommonMetaList commonMetaList = new CommonMetaList();
            DataGridViewComboBoxColumn comboBoxColumn;

            //<dataGridViewInMarketDetail>
            ERmgrUIP.ListItemCommodityDataTable listItemCommodityDataTable = commonMetaList.GetItemCommodity(true);
            comboBoxColumn = (DataGridViewComboBoxColumn)this.dataGridViewInMarketDetail.Columns[listItemCommodityDataTable.CommodityIDColumn.ColumnName];
            comboBoxColumn.DataSource = listItemCommodityDataTable;
            comboBoxColumn.DisplayMember = listItemCommodityDataTable.DescriptionOfficialColumn.ColumnName;
            comboBoxColumn.ValueMember = listItemCommodityDataTable.CommodityIDColumn.ColumnName;

            this.dataGridViewInMarketDetail.AutoGenerateColumns = false;
            inMarketDetailListView = new BindingListView<InMarketDetail>(this.inMarketBLL.InMarketDetailList);
            this.dataGridViewInMarketDetail.DataSource = inMarketDetailListView;

            StackedHeaderDecorator stackedHeaderDecorator = new StackedHeaderDecorator(this.dataGridViewInMarketDetail);

            #endregion <dataGridViewDetail>
        }


        private void InitializeReadOnlyModeBinding()
        {
            List<Control> controlList = GlobalStaticFunction.GetAllControls(this);

            foreach (Control control in controlList)
            {
                //if (control is TextBox) control.DataBindings.Add("Readonly", this, "ReadonlyMode");
                if (control is TextBox) control.DataBindings.Add("Enabled", this, "EditableMode");
                else if (control is ComboBox || control is DateTimePicker) control.DataBindings.Add("Enabled", this, "EditableMode");
                else if (control is DataGridView)
                {
                    control.DataBindings.Add("Readonly", this, "ReadonlyMode");
                    control.DataBindings.Add("AllowUserToAddRows", this, "EditableMode");
                    control.DataBindings.Add("AllowUserToDeleteRows", this, "EditableMode");
                }
            }

            this.dataListViewMaster.DataBindings.Add("Enabled", this, "ReadonlyMode");
        }

        BindingListView<InMarketDetail> inMarketDetailListView;
        
        #endregion <InitializeBinding>





        #region Import Excel

        private void ImportExcel()
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Excel File (.xlsx)|*.xlsx";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    Global.Class.Library.GlobalVariables.DistributorID = 0;
                    DialogImport03 dialogImport03 = new DialogImport03(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName);

                    if (dialogImport03.ShowDialog() == DialogResult.OK)
                    {
                        dialogImport03.Dispose();


                        DialogImport06 dialogImport06 = new DialogImport06(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName);

                        if (dialogImport06.ShowDialog() == DialogResult.OK)
                        {
                            dialogImport06.Dispose();

                            DialogImport09 dialogImport09 = new DialogImport09(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName, GlobalEnum.EIColumnID.EICommodityID, GlobalEnum.EIColumnID.EINoneID);

                            if (dialogImport09.ShowDialog() == DialogResult.OK)
                            {
                                dialogImport09.Dispose();

                                dialogImport09 = new DialogImport09(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName, GlobalEnum.EIColumnID.EIAddressAreaID, GlobalEnum.EIColumnID.EINoneID);

                                if (dialogImport09.ShowDialog() == DialogResult.OK)
                                {
                                    dialogImport09.Dispose();

                                    dialogImport09 = new DialogImport09(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName, GlobalEnum.EIColumnID.EICustomerTypeID, GlobalEnum.EIColumnID.EINoneID);

                                    if (dialogImport09.ShowDialog() == DialogResult.OK)
                                    {
                                        dialogImport09.Dispose();

                                        dialogImport09 = new DialogImport09(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName, GlobalEnum.EIColumnID.EICustomerChannelID, GlobalEnum.EIColumnID.EINoneID);

                                        if (dialogImport09.ShowDialog() == DialogResult.OK)
                                        {
                                            dialogImport09.Dispose();

                                            dialogImport09 = new DialogImport09(OleDbDatabase.MappingTaskID.InMarket, openFileDialog.FileName, GlobalEnum.EIColumnID.EICustomerID, GlobalEnum.EIColumnID.EINoneID);

                                            if (dialogImport09.ShowDialog() == DialogResult.OK)
                                            {
                                                dialogImport09.Dispose();
                                                MessageBox.Show(this, "Congratulation!" + Global.Class.Library.GlobalVariables.ImportNextStep.ToString());

                                            }

                                        }


                                    }


                                }
                            }



                        }


                    }
                }

            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }


        }








        #endregion Import Excel


        private void dataListViewMaster_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ObjectListView objectListView = (ObjectListView)sender;
                DataRowView row = (DataRowView)objectListView.SelectedObject;

                if (row != null)
                {
                    int inMarketID;

                    if (int.TryParse(row.Row["InMarketID"].ToString(), out inMarketID)) this.inMarketBLL.Fill(inMarketID);
                    else this.inMarketBLL.Fill(0);
                }
                else this.inMarketBLL.Fill(0);
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        private void dataGridViewInMarketDetail_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                using (SolidBrush b = new SolidBrush(this.dataGridViewInMarketDetail.RowHeadersDefaultCellStyle.ForeColor))
                {
                    e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 4);
                }
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        private void dataListViewMaster_DoubleClick(object sender, EventArgs e)
        {
            this.naviGroupDetails.Expanded = true;
        }




    }




}
